import json

from fileCheck import *
from WareHouseCore import *

class configLoader:
    uncommitConfigFile_buffer = []
    uncommitJsonIO_buffer = []

    # 读取出字符串文件
    def loadFile(self, configPath:str) -> int:
        # 检测文件是否存在
        if checkFile(configPath):
            # 保存文件数据
            fileReadingIO = open(configPath, "r")
            self.uncommitConfigFile_buffer.append(fileReadingIO.read())
            fileReadingIO.close()
            return len(self.uncommitConfigFile_buffer)

        else: return -255

    # 将字符串处理成字典
    def processingData(self, loadingDataIndex:int, storageWareHouse:wareHouse=None, autoCommit:bool=True) -> any:
        # 用 Json 库读取内容
        jsonIO_buffer = json.loads(self.uncommitConfigFile_buffer[loadingDataIndex - 1])

        # 判断是否自动提交
        if autoCommit and storageWareHouse is not None:
            commitID = len(storageWareHouse.commitJsonDictionary) # 获取添加 ID
            storageWareHouse.commitJsonDictionary.append(jsonIO_buffer) # 添加数据
            return commitID # 返回添加 ID

        else:
            return jsonIO_buffer # 返回处理完成的数据

    # 提交/保存数据 --> 仓库(WareHouse)
    def commitData(self, commitJsonData:any, storageWareHouse:wareHouse):
        commitID = len(storageWareHouse.commitJsonDictionary)  # 获取添加 ID
        storageWareHouse.commitJsonDictionary.append(commitJsonData)  # 添加数据
        return commitID # 返回添加 ID

    def removeCommit(self, commitID:int, storageWareHouse:wareHouse) -> bool:
        # 检测 Commit ID 是否存在
        if len(storageWareHouse.commitJsonDictionary) - 2 < commitID:
            return False
        else:
            # 移除
            storageWareHouse.commitJsonDictionary.remove(storageWareHouse.commitJsonDictionary[commitID - 1])
            return True

    # 获取字典
    def getData(self, index:int, sreachWareHouse:wareHouse) -> dict:
        return sreachWareHouse.commitJsonDictionary[index - 1]

    # 保存字典
    def saveData(self, saveFilePath:str, saveContens:dict):
        # 将 Dict 降级为字符串用来保存
        processingCompleteStr = json.dumps(saveContens, ensure_ascii=False, indent=4, separators=(',', ': '))

        # 打开文件并覆盖/写入文件
        fileIO = open(saveFilePath, "w+")
        fileIO.write(processingCompleteStr)
        fileIO.close()